package dao

import (
	"chat/app/model"
	"chat/utils"
	"errors"
	"gorm.io/gorm"
	"log"
)

// 文档：https://gorm.io/zh_CN/docs/query.html

func CommunityCreate(community *model.Community) {
	db := utils.GetDB()
	if result := db.Model(&community).Create(&community); result.Error != nil {
		log.Printf("CommunityCreate: %v", result.Error)
	}
	return
}

func CommunityGetOne(where string, args ...any) (community *model.Community, rowsAffected bool) {
	db := utils.GetDB()
	result := db.Model(&community).
		Select("id", "name", "owner_id", "icon", "memo", "create_at").
		Where(where, args...).
		Limit(1).
		Find(&community)
	rowsAffected = false
	if rows := result.RowsAffected; rows > 0 {
		rowsAffected = true
	}
	return
}

// CommunityTransactionAuto 匿名事务
// 可使用db.Transaction匿名方法来表明多个操作在一个事务里面，返回err将回滚，返回nil将提交事务
func CommunityTransactionAuto(community *model.Community, groupBatch ...any) error {
	db := utils.GetDB()
	err := db.Transaction(func(tx *gorm.DB) error {
		if result := tx.Create(&community); result.Error != nil {
			// 返回任何错误都会回滚事务
			return result.Error
		}
		if community.Id == 0 {
			return errors.New("群组创建失败")
		}
		receiveId := community.Id // 群id

		for _, val := range groupBatch {
			var contact *model.Contact
			contact = val.(*model.Contact)
			contact.ReceiveId = receiveId
			if err := tx.Create(&contact).Error; err != nil {
				// 返回任何错误都会回滚事务
				return err
			}
		}
		// 返回 nil 提交事务
		return nil
	})
	if err != nil {
		return err
	}
	return nil
}

// CommunityJoinContactList 分页查询，可以使用Limit & Offset进行分页查询
// SELECT * FROM users OFFSET 5 LIMIT 10;
func CommunityJoinContactList(limit int, offset int, where string, args ...any) (result *[]model.ResultCommunity, total int64) {
	db := utils.GetDB()

	db.Table("zhyu_community as community").
		Select("community.id, community.name, community.owner_id, community.icon, "+
			"community.memo, community.create_at, user.nickname").
		Joins("LEFT JOIN zhyu_contact as contact ON community.id = contact.receive_id").
		Joins("LEFT JOIN zhyu_user as user ON user.id = community.owner_id").
		Where(where, args...).
		Limit(limit).
		Offset(offset).
		Order("community.id desc").
		Scan(&result)

	db.Table("zhyu_community as community").
		Joins("LEFT JOIN zhyu_contact as contact ON community.id = contact.receive_id").
		Joins("LEFT JOIN zhyu_user as user ON user.id = community.owner_id").
		Select("community.id").
		Where(where, args...).
		Count(&total)
	return
}
